#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_timer.h"

#define BLINK_GPIO CONFIG_BLINK_GPIO
#define BUTTON_GPIO 23  // 使用GPIO0作为按钮输入，您可以根据实际硬件连接修改

static uint8_t s_led_state = 0;
static bool last_button_state = true;  // 按钮默认为高电平（上拉）

void app_main(void)
{
    // 初始化LED引脚
    gpio_reset_pin(BLINK_GPIO);
    gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
    
    // 初始化按钮引脚
    gpio_reset_pin(BUTTON_GPIO);
    gpio_set_direction(BUTTON_GPIO, GPIO_MODE_INPUT);
    gpio_set_pull_mode(BUTTON_GPIO, GPIO_PULLUP_ONLY);  // 启用内部上拉电阻
    
    // 设置初始LED状态
    gpio_set_level(BLINK_GPIO, s_led_state);

    while (1) {
        // 读取按钮状态
        bool current_button_state = gpio_get_level(BUTTON_GPIO);
        //printf("按钮状态: %s\n", current_button_state ? "抬起" : "按下");
        
        // 检测按钮从按下到释放的完整动作
        if (current_button_state == true && last_button_state == false) {
            // 按钮被释放，切换LED状态
            s_led_state = !s_led_state;
            gpio_set_level(BLINK_GPIO, s_led_state);
            printf("LED状态: %s\n", s_led_state ?  "关": "开");
        }
        
        // 更新按钮状态
        last_button_state = current_button_state;
        
        // 短暂延时以防止按钮抖动
        vTaskDelay(20 / portTICK_PERIOD_MS);
    }
}
